package com.guigu.qingcheng.controller;

import com.guigu.qingcheng.service.SkuSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

@Controller
public class SearchController {

    @Autowired
    private SkuSearchService skuSearchService;

    /**
     * 处理search页的搜索
     * @param model
     * @param searchMap
     * @return
     * @throws Exception
     */
    @GetMapping("/search")
    public String search(Model model, @RequestParam Map<String, String>
            searchMap) throws Exception {
        Map result = skuSearchService.search(searchMap);
        model.addAttribute("result", result);

        //页面传递给后端的两个参数，sort排序字段  sortOrder排序规则
        if (searchMap.get("sortOrder")==null||searchMap.get("sortOrder")==""){//排序规则
            searchMap.put("sortOrder","DESC");
        }

        if (searchMap.get("sort")==null||searchMap.get("sort")==""){//排序字段
            searchMap.put("sort","");
        }

        //url处理
        StringBuffer url = new StringBuffer("/portal/search?");
        for (String key:searchMap.keySet()) {
            url.append("&"+key+"="+searchMap.get(key));
        }
        model.addAttribute("url",url);

        //页码
        int pageNo = Integer.parseInt(searchMap.get("pageNo"));
        model.addAttribute("pageNo",pageNo);

        //得到总页数
        Long totalPages = (Long) result.get("totalPages");

        //开始页码
        int startPage = 1;
        //截至页码
        int endPage = totalPages.intValue();

        if (totalPages>5){
            startPage = pageNo-2;
            if (startPage<1){
                startPage = 1;
            }
            endPage = startPage +4;
        }

        model.addAttribute("startPage",startPage);
        model.addAttribute("endPage",endPage);

        model.addAttribute("searchMap",searchMap);
        return "search";
    }
}
